const cron = require('node-cron');
import axios from 'axios';
import { checkTodayWhereCommit } from '../utils/checkTodayWhereCommit';
import { stateOptions } from '../global/formatResJson';

cron.schedule(`0 ${process.env.AUTO_COMMIT_HOUR} * * *`, async () => {
	if (!checkTodayWhereCommit()) return;

	const { AUTO_COMMIT_MIN_COUNT, AUTO_COMMIT_MAX_COUNT } = process.env;
	let min_count = Number(AUTO_COMMIT_MIN_COUNT);
	let max_count = Number(AUTO_COMMIT_MAX_COUNT);
	if (isNaN(min_count) || min_count < 0) min_count = 0;
	if (isNaN(max_count) || max_count > 30) max_count = 30;

	try {
		const commitRes = await axios({
			baseURL: `http://localhost:${process.env.PORT}`,
			url: '/commit',
			params: { commitCount: Math.floor(Math.random() * (max_count - min_count + 1)) + min_count },
		});

		if (commitRes.data.code === stateOptions.Fail) throw new Error(commitRes.data.msg);
	} catch (e: any) {
		console.error(`${moment_g().format('YYYY-MM-DD HH:mm:ss')} -> 定时任务请求异常:${e?.message}`);
	}
});
